package com.youdianstar.app.ui.account

import android.app.Activity
import android.content.Intent
import androidx.lifecycle.Observer
import com.youdianstar.app.common.Extra
import com.youdianstar.app.common.HttpCode
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.common.entity.UserInfo
import com.youdianstar.app.common.ex.getViewColor
import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver

import com.youdianstar.app.common.util.StrUtil
import com.youdianstar.app.BR
import com.youdianstar.app.R
import com.youdianstar.app.databinding.ActivityChangeStep1Binding
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.common.auko.startActivity
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: ChangeStep1Activity
 * Author: 82149 Create: 2023/7/24 11:44
 * Changes (from 2023/7/24)
 * --------------------------------------------------
 * description: 修改账号  :邮箱/手机  ,步骤1 验证旧账号
 * ---------------------------------------------------
 *
 */
class ChangeStep1Activity : BaseActivity<ActivityChangeStep1Binding, LoginViewModel>() {
    override fun layoutId(): Int = R.layout.activity_change_step1

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): LoginViewModel {
        val model: LoginViewModel by viewModel()
        return model
    }

    // 0 :Phone number ,1 :Email
    private var accountType: Int = 0
    private var userInfo: UserInfo? = null

    private val REQUEST_CODE = 0x18
    private var countryCode: String? = null

    override fun initData() {
        super.initData()
        accountType = intent.getIntExtra(Extra.IT_TYPE, 0)
        mViewModel.selectPhoneField.set(accountType == 0)
        mBinding.headBar.initTitle(this,
            getString(if (accountType == 1) R.string.profile_changeLoginEmail else R.string.profile_changePhoneNum)
        )
        if (accountType == 1) {
            mBinding.tvStepContent.text = getString(R.string.profile_verifyEmail)
        } else {
            mBinding.tvStepContent.text = getString(R.string.profile_verifyPhoneNum)
        }

        userInfo = DataAppManager.instance.getUser()
        userInfo?.let { user ->
            if (accountType == 0) {
                val phoneCode: String = user.code?.toString() ?: DataAppManager.instance.getPhoneCode()
                countryCode = if (StrUtil.isEmpty(phoneCode)) "1" else  phoneCode
                mBinding.tvPhoneCode.text = "+$countryCode"
                mViewModel.phoneDataField.set(user.phone ?: "")
            } else {
                mViewModel.emailDataField.set(user.email ?: "")
            }
        }
    }

    override fun initClickEvent() {
        mBinding.btnAction.setThrottleListener {
            val isSelectPhone = mViewModel.selectPhoneField.get() ?: true
            val phoneFiled = mViewModel.phoneDataField.get()
            val emailFiled = mViewModel.emailDataField.get()
            val otpPhoneFiled = mViewModel.otpPhoneField.get()
            val otpEmailFiled = mViewModel.otpEmailField.get()

            if (isSelectPhone && StrUtil.isEmpty(phoneFiled)) {
                toastShow(getString(R.string.toast_requiredPhone))
                return@setThrottleListener
            }
            if (isSelectPhone && !StrUtil.isEmpty(phoneFiled) && phoneFiled!!.length < 8) {
                toastShow(getString(R.string.toast_validPhone))
                return@setThrottleListener
            }

            if (!isSelectPhone && StrUtil.isEmpty(emailFiled)) {
                toastShow(getString(R.string.toast_requiredEmail))
                return@setThrottleListener
            }

            if (!isSelectPhone && !StrUtil.emailFormat(emailFiled)) {
                toastShow(getString(R.string.toast_validEmail))
                return@setThrottleListener
            }

            if (isSelectPhone) {
                if (StrUtil.isEmpty(otpPhoneFiled)){
                    toastShow(getString(R.string.toast_requiredCode))
                    return@setThrottleListener
                }
                if (otpPhoneFiled!!.length < 4){
                    toastShow(getString(R.string.toast_validCode))
                    return@setThrottleListener
                }
            }

            if (!isSelectPhone) {
                if (StrUtil.isEmpty(otpEmailFiled)){
                    toastShow(getString(R.string.toast_requiredCode))
                    return@setThrottleListener
                }
                if (otpEmailFiled!!.length < 4){
                    toastShow(getString(R.string.toast_validCode))
                    return@setThrottleListener
                }
            }

            showLoadingDialog("")
            //校验原账号
            mViewModel.verifyAccount(
                    code = if (isSelectPhone) countryCode else null,
                    phone = if (isSelectPhone) phoneFiled else null,
                    email = if (isSelectPhone) null else emailFiled,
                    msgCode = if (isSelectPhone) otpPhoneFiled!! else otpEmailFiled!!
            )
            hideSoftKeyboard(this)
        }


        mBinding.phoneSendOtp.setThrottleListener {
            //点击发送OTP判断
            val phoneFiled = mViewModel.phoneDataField.get()
            if (StrUtil.isEmpty(phoneFiled)) {
                toastShow(getString(R.string.toast_requiredPhone))
                return@setThrottleListener
            }
            if (!StrUtil.isEmpty(phoneFiled) && phoneFiled!!.length < 5) {
                toastShow(getString(R.string.toast_validPhone))
                return@setThrottleListener
            }
            showLoadingDialog("")
            mViewModel.getOTPCode(countryCode ?: "1", phoneFiled ?: "", "binding")
        }

        mBinding.emailSendOtp.setThrottleListener {
            //点击发送OTP判断
            val emailFiled = mViewModel.emailDataField.get()
            if (StrUtil.isEmpty(emailFiled)) {
                toastShow(getString(R.string.toast_requiredEmail))
                return@setThrottleListener
            }
            if (!StrUtil.emailFormat(emailFiled)) {
                toastShow(getString(R.string.toast_validEmail))
                return@setThrottleListener
            }
            showLoadingDialog("")
            // TODO: 邮箱OTP功能需要新的API接口支持
            // mViewModel.getOTPCode("", emailFiled, "email")
        }
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.phoneCountEvent.observe(this, Observer {
            if (it == -1L) {
                mBinding.phoneSendOtp.isEnabled = true
                mBinding.phoneSendOtp.text = getString(R.string.login_get)
            } else {
                var time = "$it"
                if (time.length == 1) {
                    time = "0$it"
                }
                mBinding.phoneSendOtp.isEnabled = false
                mBinding.phoneSendOtp.text = time + "s"
            }
        })

        mViewModel.emailCountEvent.observe(this, Observer {
            if (it == -1L) {
                mBinding.emailSendOtp.isEnabled = true
                mBinding.emailSendOtp.text = getString(R.string.login_get)
            } else {
                var time = "$it"
                if (time.length == 1) {
                    time = "0$it"
                }
                mBinding.emailSendOtp.isEnabled = false
                mBinding.emailSendOtp.text = time + "s"
            }
        })

        mViewModel.otpPhoneResultData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                mViewModel.onPhoneOtpSuccess()
                mViewModel.downCountPhone()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
                if (code == HttpCode.CODE_OTP_UNABLE || code == HttpCode.CODE_OTP_OVER) {
                    mBinding.phoneSendOtp.isClickable = false
                    mBinding.phoneSendOtp.setTextColor(getViewColor(this@ChangeStep1Activity,R.color.text_hint_input))
                }
            }
        })

        mViewModel.otpEmailResultData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                mViewModel.onEmailOtpSuccess()
                mViewModel.downCountEmail()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
                if (code == HttpCode.CODE_OTP_UNABLE || code == HttpCode.CODE_OTP_OVER) {
                    mBinding.emailSendOtp.isClickable = false
                    mBinding.emailSendOtp.setTextColor(getViewColor(this@ChangeStep1Activity,R.color.text_hint_input))
                }
            }
        })

        mViewModel.verifyResultLiveData.observe(this, object : BaseApiResultObserver<Any>(true) {
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                dismissDialog()
                val isSelectPhone = mViewModel.selectPhoneField.get() ?: true
                if (isSelectPhone){
                    startActivity<ChangeStep2Activity>(Extra.IT_TYPE to 0,Extra.IT_Link to false)
                }else{
                    startActivity<ChangeStep2Activity>(Extra.IT_TYPE to 1,Extra.IT_Link to false)
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            countryCode = data?.getStringExtra(Extra.IT_CODE)
            mBinding.tvPhoneCode.text = "+$countryCode"
        }
    }


}